<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户昵称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户电话" prop="userTel">
        <el-input
          v-model="queryParams.userTel"
          placeholder="请输入用户电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会员名称" prop="vipName">
        <el-input
          v-model="queryParams.vipName"
          placeholder="请输入会员名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="注册时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeUserCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="frontUserList" @selection-change="handleSelectionChange">
      <el-table-column label="用户昵称" align="center" prop="userName" />
      <el-table-column label="用户姓名" align="center" prop="userRealName" />
      <el-table-column label="手机号" width="150px" align="center" prop="userTel" />
      <el-table-column label="类型" align="center" prop="vipStatus" :formatter="formatVipStatus"/>
      <el-table-column label="用户积分" align="center" prop="userPoints" />
      <el-table-column label="用户余额" align="center" prop="userBalance" />
      <el-table-column label="用户性别" align="center" prop="userSex" :formatter="formatSex"/>
<!--      <el-table-column label="用户邮箱" align="center" prop="userEmail" />-->
      <el-table-column label="用户注册时间" align="center" prop="userCreateTime" width="180"/>
      <el-table-column label="最后登录时间" align="center" prop="lastLoginTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary"  @click="handleUpdate(scope.row)" v-hasPermi="['order:frontUser:edit']">编辑</el-button>
          <el-button link type="primary" v-if="scope.row.vipStatus === 1"
                     @click="handleVipOperation(scope.row, true)"
                     v-hasPermi="['order:frontUser:vip']">续费会员</el-button>
          <el-button link type="primary"
                     v-else @click="handleVipOperation(scope.row, false)"
                     v-hasPermi="['order:frontUser:vip']">开通会员</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户列表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="frontUserRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="昵称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="姓名" prop="userRealName">
          <el-input v-model="form.userRealName" placeholder="请输入用户真实姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="form.userEmail" placeholder="请输入用户邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 续费或者充值会员对话框 -->
    <el-dialog :title="vipDialogTitle" v-model="open2" width="500px" append-to-body>
      <el-form ref="vipFormRef" :model="vipForm" :rules="vipRules" label-width="80px">
        <el-form-item label="会员选择" prop="vipId">
          <el-select v-model="vipForm.vipId" placeholder="请选择会员类型">
            <el-option v-for="vip in vipList" :key="vip.vipId" :label="getVipTypeName(vip.vipName)" :value="vip.vipId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="续费时间" prop="months">
          <el-input v-model.number="vipForm.months" placeholder="请输入续费月份" type="number" min="1"/>
          <div slot="helper">单位：月，最少1个月</div>
        </el-form-item>
        <el-form-item label="充值余额" prop="balance">
          <el-input v-model.number="vipForm.balance" placeholder="请输入充值金额" type="number" min="0"/>
          <div slot="helper">单位：元，可输入0</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelVip">取消</el-button>
          <el-button type="primary" @click="submitVipForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FrontUser">
import { listFrontUser, getFrontUser, delFrontUser, addFrontUser, updateFrontUser } from "@/api/order/frontUser"
import { listVip } from "@/api/order/vip.js";

const { proxy } = getCurrentInstance()

const frontUserList = ref([])
const open = ref(false)
const open2 = ref(false)
const vipDialogTitle = ref("会员开通") // 会员对话框标题
const isRenew = ref(false) //是否是开通会员
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("编辑")
const daterangeUserCreateTime = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    userTel: null,
    vipStatus: null,
    vipName: null,
    userCreateTime: null,
  },
  rules: {
    userName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" }
    ],
    userTel: [
      { required: true, message: "用户电话不能为空", trigger: "blur" }
    ],
    userAccount: [
      { required: true, message: "用户账户不能为空", trigger: "blur" }
    ],
    userPassword: [
      { required: true, message: "用户登录密码不能为空", trigger: "blur" }
    ],
  }
})

// 会员相关变量
const vipList = ref([]) // 会员类型列表
const vipForm = ref({
  userId: null, // 关联的用户ID
  vipId: null, // 会员类型ID
  months: 1, // 续费月份，默认1个月
  balance: 0 // 充值余额，默认0
})

const vipRules = ref({
  vipId: [
    { required: true, message: "请选择会员类型", trigger: "change" }
  ],
  months: [
    { required: true, message: "请输入续费月份", trigger: "blur" },
    { type: "number", min: 1, message: "最少续费1个月", trigger: "blur" }
  ],
  balance: [
    { required: true, message: "请输入充值金额", trigger: "blur" },
    { type: "number", min: 0, message: "充值金额不能为负数", trigger: "blur" }
  ]
})

const { queryParams, form, rules } = toRefs(data)

// 将数字类型的 vipName 转换为具体的会员名称
function getVipTypeName(vipName) {
  switch(vipName) {
    case 1: return '普通会员';
    case 2: return '黄金会员';
    case 3: return '钻石会员';
    default: return '未知会员';
  }
}

// 根据vip状态显示不同内容
function formatVipStatus(row, column) {
  const status = row.vipStatus;
  switch(status) {
    case 0:
      return '普通用户';
    case 1:
      return 'VIP会员';
    case 2:
      return '过期会员';
    default:
      return '未知状态'; // 处理未定义的情况
  }
}
// 根据sex状态显示不同内容
function formatSex(row, column) {
  const status = row.vipStatus;
  switch(status) {
    case 0:
      return '未知';
    case 1:
      return '男';
    case 2:
      return '女';
    default:
      return '未知'; // 处理未定义的情况
  }
}

/** 查询用户列表列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeUserCreateTime && '' != daterangeUserCreateTime) {
    queryParams.value.params["beginUserCreateTime"] = daterangeUserCreateTime.value[0]
    queryParams.value.params["endUserCreateTime"] = daterangeUserCreateTime.value[1]
  }
  listFrontUser(queryParams.value).then(response => {
    frontUserList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    userId: null,
    userName: null,
    userTel: null,
    userAccount: null,
    userPoints: null,
    totalBalance: null,
    totalConsume: null,
    totalPoints: null,
    consumePoints: null,
    userPassword: null,
    paymentPassword: null,
    vipStatus: null,
    vipName: null,
    vipId: null,
    vipStartTime: null,
    vipEndTime: null,
    userBalance: null,
    userAvatar: null,
    userRealName: null,
    userSex: null,
    userEmail: null,
    userCreateTime: null,
    userUpdateTime: null,
    lastLoginTime: null,
    roles: null
  }
  proxy.resetForm("frontUserRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeUserCreateTime.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}


/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _userId = row.userId || ids.value
  console.log("userId1",row.userId)
  console.log("userId2",_userId)
  getFrontUser(_userId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "编辑用户信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["frontUserRef"].validate(valid => {
    if (valid) {
      if (form.value.userId != null) {
        updateFrontUser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addFrontUser(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _userIds = row.userId || ids.value
  proxy.$modal.confirm('是否确认删除用户列表编号为"' + _userIds + '"的数据项？').then(function() {
    return delFrontUser(_userIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 打开会员操作对话框 */
function handleVipOperation(row, isRenewal) {
  if (isRenewal) {
    isRenew.value = true;
  }
  // 重置表单
  resetVipForm()
  // 设置用户ID
  vipForm.value.userId = row.userId
  // 根据用户当前会员状态设置对话框标题
  vipDialogTitle.value = isRenewal ? "会员续费" : "会员开通"
  // 加载会员类型列表
  loadVipList()
  // 打开对话框
  open2.value = true
}

/** 加载会员类型列表 */
function loadVipList() {
  listVip().then(response => {
    vipList.value = response.rows
    // 设置默认选中第一项
    if (vipList.value.length > 0) {
      vipForm.value.vipId = vipList.value[0].vipId;
    }
  })
}

/** 重置会员表单 */
function resetVipForm() {
  vipForm.value = {
    userId: null,
    vipId: null,
    months: 1,
    balance: 0
  }
  if (proxy.$refs["vipFormRef"]) {
    proxy.resetForm("vipFormRef")
  }
}

/** 取消会员操作 */
function cancelVip() {
  open2.value = false
  resetVipForm()
}

/** 提交会员操作表单 */
function submitVipForm() {
  proxy.$refs["vipFormRef"].validate(valid => {
    if (valid) {
      // 找到选中的会员类型
      const selectedVip = vipList.value.find(vip => vip.vipId === vipForm.value.vipId);
      if (!selectedVip) {
        proxy.$modal.msgError("请选择有效的会员类型");
        return;
      }

      // 获取当前用户信息
      getFrontUser(vipForm.value.userId).then(response => {
        const userInfo = response.data;
        const now = new Date();

        // 格式化时间为精确到秒的格式 (YYYY-MM-DD HH:mm:ss)
        const formatTime = (date) => {
          return date.toISOString().slice(0, 19).replace('T', ' ');
        };

        // 计算会员结束时间
        let endTime;
        if (isRenew.value) {
          // 续费：在原有结束时间基础上增加月份
          endTime = userInfo.vipEndTime ? new Date(userInfo.vipEndTime) : now;
        } else {
          // 开通：从当前时间开始
          userInfo.vipStartTime = formatTime(now); // 设置开始时间为当前时间（精确到秒）
          endTime = new Date(now); // 从当前时间计算结束时间
        }

        // 计算增加月份后的结束时间
        endTime.setMonth(endTime.getMonth() + vipForm.value.months);

        // 构造更新的数据对象
        const updateData = {
          userId: vipForm.value.userId,
          vipStatus: 1, // 设置为VIP会员状态
          vipName: getVipTypeName(selectedVip.vipName), // 设置具体会员名称
          vipStartTime: userInfo.vipStartTime,
          vipEndTime: formatTime(endTime), // 结束时间精确到秒
          // 如果有充值余额，更新用户余额
          userBalance: vipForm.value.balance > 0
              ? (userInfo.userBalance || 0) + vipForm.value.balance
              : userInfo.userBalance
        };

        // 调用更新用户接口
        updateFrontUser(updateData).then(() => {
          proxy.$modal.msgSuccess(isRenew.value ? "会员续费成功" : "会员开通成功");
          open2.value = false;
          getList(); // 刷新用户列表
        }).catch(error => {
          proxy.$modal.msgError(isRenew.value ? "会员续费失败" : "会员开通失败");
          console.error(error);
        });
      }).catch(error => {
        proxy.$modal.msgError("获取用户信息失败");
        console.error(error);
      });
    }
  });
}

getList()
</script>
